<?php

function shop_get_categories($parent_id, $current_path, $level, $ancestor=1) {
	global $db, $site, $path;
	
	$categories = $db->fetchAll("SELECT *, 'shop' AS context FROM shop_categories c WHERE site_id=? AND parent_id=? HAVING (SELECT COUNT(*) FROM shop_categories_products cp JOIN shop_products p ON cp.product_id=p.id WHERE category_id=c.id AND p.active=1 AND p.deleted=0)>0 ORDER BY sort, title", array($site['id'], $parent_id));
	for($i=0;$i<count($categories);$i++) {
		$categories[$i]['full_path'] = $current_path . $categories[$i]['path'] . '/';
		$categories[$i]['ancestor'] = 0;
		if (isset($path[$level]) and $path[$level] == $categories[$i]['path']) {
			if ($ancestor) { $categories[$i]['ancestor'] = 1; } 
			if (!isset($path[$level+1])) {
				// this is the last element in the path, so it's also active
				$categories[$i]['active'] = 1;
			}
			$category = $categories[$i];
		}
		$categories[$i]['children'] = shop_get_categories($categories[$i]['id'], $categories[$i]['full_path'], $level+1, $categories[$i]['ancestor']);
	}
	return $categories;
}

$root_category_id = $db->fetchOne("SELECT id FROM shop_categories WHERE site_id=? AND parent_id=0", $site['id']);
return shop_get_categories($root_category_id, $navigation_prefix, substr_count($navigation_prefix, '/')-1);
